package com.safe.app.controller.index;

import com.safe.app.config.ResultBean;
import com.safe.app.config.context.ExecutionContext;
import com.safe.app.config.init.redis.RedisServer;
import com.safe.app.controller.BaseController;
import com.safe.app.model.User;
import com.safe.app.service.UserService;
import com.safe.app.utils.constants.SystemConstant;
import com.safe.app.utils.exceptions.base.BadRequestException;
import com.safe.app.utils.exceptions.base.NoAuthException;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 对外开放入口，不做登陆拦截
 *
 * @author h2l
 */
@RequestMapping("/index")
@Controller
@Slf4j
public class IndexController extends BaseController {

    @Autowired
    private UserService loginService;
    @Autowired
    private RedisServer redisServer;

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultBean login(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject jsonObject) throws Exception {
        String loginName = jsonObject.optString("loginName");
        String passWord = jsonObject.optString("passWord");
        if (StringUtils.isBlank(loginName) || StringUtils.isBlank(passWord)) {
            throw new BadRequestException("loginName or passWord can not be empty");
        }
        User user = loginService.login(loginName, passWord);
        if (user == null) {
            throw new NoAuthException("登陆失败,账户或者密码错误");
        }
        HttpSession session = getSession(request);
        //session id设置对应的登陆信息校验规则
        request.getSession().setAttribute(SystemConstant.SAFE_APP_SESSION_ID, session.getId());
        redisServer.set(SystemConstant.SAFE_APP_SESSION_ID + session.getId(), user, 60 * 60 * 10);
        ExecutionContext.setLoginUser(user);
        ExecutionContext.setUserId(user.getUserId());
        User loginUser = new User();
        loginUser.setUserName(user.getUserName());
        loginUser.setHeadImgUrl(user.getHeadImgUrl());
        loginUser.setPhoneNumber(user.getPhoneNumber());
        log.info("登陆成功，当前用户：【" + loginUser.getUserName() + "】");
        return new ResultBean(loginUser);
    }


}
